<template>
  <div class="about-box">
    <div class="about-left">
      <div class="selectTime">
        <span>消费时间</span>
        <t-date-picker v-model="orderTime" />
      </div>
      <div class="left-heard">
        <div class="heard-left">
          <span v-if="!userInfo.member_id">散客</span>
          <p v-if="userInfo.member_id">{{ userInfo.nickname }}</p>
          <p v-if="userInfo.member_id">{{ userInfo.member_level_name }}</p>
        </div>
        <div class="heard-right" @click="visible = true">查询会员</div>
      </div>

      <div class="left-content">
        <div class="content-item" v-for="(item, index) in ActiveList" :key="item.goods_id">
          <img class="img-box" :src="'https://cqshop.360daypay.com/' + item.goods_image" />

          <div class="item-content">
            <div class="item-conetnt-top">
              <span class="name-box">{{ item.goods_name }}</span>
              <span class="del" @click="delItem(index)">删除</span>
            </div>
            <div class="item-conetnt-bottom">
              <span class="price-1"
                >￥{{
                  userInfo.member_level === 1
                    ? item.member_price_config[`${userInfo.member_level}`]
                    : userInfo.member_level === 2
                    ? item.member_price_config['2']
                    : item.member_price_config[`${userInfo.member_level}`]
                }}</span
              >
              <span class="price-2">库存{{ item.stock }}</span>
              <div class="price-count">
                <div class="count-1" @click="countType(1, index)">-</div>
                <div class="count-2">
                  {{ item.num }}
                </div>
                <div class="count-3" @click="countType(2, index)">+</div>
              </div>
            </div>
          </div>
        </div>
        <span class="null-title" v-if="ActiveList.length < 1">点击右侧商品，选择商品进行结账</span>
      </div>
      <div class="bottom">
        <div class="btm-price" @click="ActiveList.length < 1 ? (visible2 = false) : (visible2 = true)">
          <span class="btm-price-left">合计 {{ getNum }} 件</span>
          <span class="btm-price-right">￥ {{ getPriceNumber - preferential + preferentialNew2 }} 元</span>
        </div>
        <div class="btm-btn">
          <div class="btn-1">
            <t-button @click="payList" :loading="loading" block theme="primary" variant="base">下单</t-button>
          </div>
        </div>
      </div>
    </div>
    <div class="about-right">
      <div class="right-heard">
        <t-input v-model="parmas.goods_name" placeholder="请输入商品关键字" :clearable="false" @Enter="onEnter">
          <template #suffixIcon>
            <search-icon @click="onEnter" :style="{ cursor: 'pointer' }" />
          </template>
        </t-input>
      </div>
      <div class="right-content">
        <div class="right-content-left">
          <div
            class="tab-item"
            @click="setcategory_id(item.category_id)"
            :class="{ active: parmas.category_id === item.category_id }"
            v-for="(item, index) in tabList"
            :key="index"
          >
            <span>{{ item.category_name }}</span>
          </div>
        </div>
        <div class="right-content-tight">
          <div class="good-list">
            <t-row :gutter="16">
              <t-col :span="6" v-for="item in goodList" :key="item">
                <div class="good-item" :class="{ 'item-active': isOpen(item.goods_id) }" @click="addActive(item)">
                  <img class="good-item-img" :src="'https://cqshop.360daypay.com/' + item.goods_image" />

                  <div class="good-item-right">
                    <p class="good-item-right-name">{{ item.goods_name }}</p>
                    <div class="good-item-num">
                      <span class="good-item-num-price">￥{{ item.price }}</span>
                      <!-- {{
                          userInfo.member_level === 1
                            ? item.member_price_config['1']
                            : userInfo.member_level === 2
                            ? item.member_price_config['2']
                            : item.member_price_config['3']
                        }} -->
                      <span>库存：{{ item.goods_stock }}</span>
                    </div>
                  </div>
                </div>
              </t-col>
            </t-row>
          </div>
          <t-row :gutter="16" style="margin-top: 20px">
            <t-col :span="12">
              <t-pagination
                :showPageSize="false"
                v-model="parmas.page"
                v-model:pageSize="parmas.page_size"
                :total="total"
                @change="onChange"
                @page-size-change="onPageSizeChange"
                @current-change="onCurrentChange"
              />
            </t-col>
          </t-row>
        </div>
      </div>
    </div>
  </div>
  <div class="loadai">
    <t-dialog :confirmBtn="null" v-model:visible="visible" header="会员查询" style="width: 340px" v-if="visible">
      <div class="center-box">
        <div class="mobile-box">
          <span>手机号:</span>
          <t-input placeholder="请输入手机号或手机号后四位进行查询" v-model="mobile" />
        </div>
        <div class="seach seach-mg">
          <t-button :loading="loading" block theme="primary" variant="base" @click="seachVip">查询</t-button>
        </div>
      </div>
      <template #footer>
        <div class="login" @click="cheakout">
          <div class="login-item">
            <t-icon name="user-add" size="24px"></t-icon>
            <span>会员注册</span>
          </div>
        </div>
      </template>
    </t-dialog>
    <t-dialog
      :confirmBtn="null"
      v-model:visible="visible1"
      header="会员查询"
      style="width: 340px"
      @close="close"
      v-if="visible1"
    >
      <t-form ref="form" :colon="true">
        <t-form-item label="姓名">
          <t-input v-model="vipInfo.nickname" placeholder="请输入内容"></t-input>
        </t-form-item>

        <t-form-item label="手机号码">
          <t-input v-model="vipInfo.mobile" placeholder="请输入内容"></t-input>
        </t-form-item>
        <t-form-item label="性别" name="gender">
          <t-radio-group v-model="vipInfo.sex">
            <t-radio value="1">男</t-radio>
            <t-radio value="2">女</t-radio>
          </t-radio-group>
        </t-form-item>
        <t-form-item label="生日">
          <t-date-picker v-model="vipInfo.birthday" />
        </t-form-item>
        <t-form-item label="会员等级">
          <t-select v-model="vipInfo.member_level" @Change="onChangelevel">
            <t-option v-for="item in vipTab" :key="item.level_id" :label="item.level_name" :value="item.level_id" />
          </t-select>
          <!-- <t-input v-model="vipInfo.vip" placeholder="请输入内容" @enter="onEnter"></t-input> -->
        </t-form-item>
      </t-form>
      <template #footer>
        <div class="seach">
          <t-button :loading="loading" block theme="primary" variant="base" @click="addMemberLogin">确定录入</t-button>
        </div>
      </template>
    </t-dialog>
    <t-dialog :confirmBtn="null" v-model:visible="skuOpen" header="选择" style="width: 840px">
      <div class="content-box" v-if="selectList.sku_list.length > 0">
        <div class="content-box-heard">
          <!-- skuIndex -->
          <img class="good-item-img" :src="'https://cqshop.360daypay.com/' + selectList.sku_list[skuIndex].sku_image" />

          <div class="good-item-right">
            <p class="good-item-right-name">{{ selectList.goods_name }}</p>
            <div class="good-item-num">
              <span class="good-item-num-price"
                >￥{{
                  userInfo.member_level === 1
                    ? selectList.sku_list[skuIndex].member_price_config['1']
                    : userInfo.member_level === 2
                    ? selectList.sku_list[skuIndex].member_price_config['2']
                    : selectList.sku_list[skuIndex].member_price_config[`${userInfo.member_level}`]
                }}</span
              >
              <span>库存：{{ selectList.sku_list[skuIndex].stock }}</span>
            </div>
          </div>
        </div>
        <div class="sku-list sku-list-mg">
          <span class="sku-list-select">选择</span>
        </div>
        <div class="sku-list">
          <data
            @click="skuIndex = index"
            class="sku-item"
            :class="{ 'sku-item-active': index === skuIndex }"
            v-for="(item, index) in selectList.sku_list"
            :key="index"
            >{{ item.sku_name }}</data
          >
        </div>
      </div>
      <template #footer>
        <div class="seach">
          <t-button :loading="loading" block theme="primary" variant="base" @click="addSku">确定</t-button>
        </div>
      </template>
    </t-dialog>
    <t-dialog
      :confirmBtn="null"
      v-model:visible="visible2"
      header="优惠调整"
      style="width: 340px"
      @close="close2"
      v-if="visible2"
    >
      <t-form ref="form" :colon="true">
        <t-form-item label="优惠金额">
          <t-input-number
            @Change="numberChange"
            v-model="preferentialNew"
            :max="getPriceNumbergetPriceNumber"
            :min="0"
            theme="normal"
          ></t-input-number>
        </t-form-item>
        <t-form-item label="配送费用">
          <t-input-number
            @Change="numberChange1"
            v-model="preferentialNew2"
            :max="getPriceNumbergetPriceNumber"
            :min="0"
            theme="normal"
          ></t-input-number>
        </t-form-item>
      </t-form>
      <div class="preferential-box">
        <div class="preferential-item">
          <span>费用总额:￥ {{ getPriceNumber }} 元</span>
        </div>
        <div class="preferential-item">
          <span>配送费用:￥ {{ preferentialNew2 }} 元</span>
        </div>
        <div class="preferential-item">
          <span>优惠金额:￥ </span>
          <span style="color: #e62b17">{{ preferentialNew }} </span>
          <span>元</span>
        </div>
        <div class="preferential-item">
          <span>实付:￥ {{ Number(getPriceNumber - preferentialNew + preferentialNew2) }} 元</span>
        </div>
      </div>

      <template #footer>
        <div class="seach">
          <t-button :loading="loading" block theme="primary" variant="base" @click="addpreferential">确定录入</t-button>
        </div>
      </template>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { getNewTime } from '@/utils/date';
import { MessagePlugin } from 'tdesign-vue-next';
import {
  lists,
  getgoodslists,
  getGoodsSku,
  calculate,
  vipLists,
  searchMemberByMobile,
  addMember,
  createOrder,
} from '@/api/goods/goods';
import { SearchIcon } from 'tdesign-icons-vue-next';
import { urls } from '@/utils/request/upload';
import { ref, reactive, computed } from 'vue';
import { useRoute } from 'vue-router';
import { getBanner, contentData } from '@/api/banner/banner';
const userInfo = ref({
  member_id: 0,
  nickname: '',
  member_level: 1,
  member_level_name: '普通会员',
});
const LeftList = ref([{ sku_id: 8, num: 2 }]);
const mobile = ref('');
const skuOpen = ref(false);
const selectList = ref({ sku_list: [], goods_id: 0 });
const skuIndex = ref(0);
const skuNumber = ref(1);
const parmas = reactive({
  page: 1,
  page_size: 8,
  category_id: 0,
  goods_name: '',
});
const loading = ref(false);
const orderTime = ref(''); //下单时间
orderTime.value = getNewTime();
const tabList = ref([{ category_name: '所有分类', category_id: 0 }]);
const vipTab = ref([]);
let vipInfo = reactive({
  nickname: '',
  mobile: '',
  sex: 0,
  birthday: '',
  member_level: 1,
  member_level_name: '普通会员',
});

const ActiveList = ref([]);
const visible = ref(false);
const visible1 = ref(false);
const visible2 = ref(false);
const preferential = ref(0);
const preferentialNew = ref(0);
const preferentialNew2 = ref(0);
const total = ref(0); //商品总数
const textInfo = ref('');
const cruuent = ref(3);
const route = useRoute();
const goodList = ref([]);
const current = ref(1);
const pageSize = ref(5);
const orderPrice = ref(0); //总价
const close = () => {
  visible1.value = false;
  vipInfo = {
    nickname: '',
    mobile: '',
    sex: 0,
    birthday: '',
    member_level: 1,
    member_level_name: '普通会员',
  };
};
const close2 = () => {
  preferentialNew.value = preferential.value;
  visible2.value = false;
};
const numberChange = () => {
  if (!preferentialNew.value && preferentialNew.value !== 0) {
    preferentialNew.value = 0;
  }
  let nums = getPriceNumberreturn();
  if (preferentialNew.value > nums) {
    preferentialNew.value = nums;
  }
};
const numberChange1 = () => {
  if (!preferentialNew2.value && preferentialNew2.value !== 0) {
    preferentialNew2.value = 0;
  }
};
const addpreferential = () => {
  preferential.value = preferentialNew.value;
  visible2.value = false;
};
const onPageSizeChange = (size) => {
  console.log('page-size:', size);
};
const isOpen = (id) => {
  let isShow = false;
  ActiveList.value.forEach((el) => {
    if (el.goods_id == id) {
      isShow = true;
    }
  });
  return isShow;
};
const isOpensku_id = (id) => {
  let isShow = false;
  ActiveList.value.forEach((el) => {
    if (el.sku_id == id) {
      isShow = true;
    }
  });
  return isShow;
};
const getNum = computed(() => {
  let NUMS = 0;
  ActiveList.value.forEach((el) => {
    NUMS = NUMS + el.num;
  });

  return NUMS;
});
const getPriceNumber = computed(() => {
  let price: any = 0;
  if (userInfo.value.member_level === 1) {
    ActiveList.value.forEach((el) => {
      if (el.member_price_config) {
        el.price = Number(el.member_price_config[`${userInfo.value.member_level}`]);
        price = price + el.num * Number(el.member_price_config['1']);
      }
    });
  } else if (userInfo.value.member_level === 2) {
    ActiveList.value.forEach((el) => {
      if (el.member_price_config) {
        el.price = Number(el.member_price_config['2']);
        price = price + el.num * Number(el.member_price_config['2']);
      }
    });
  } else {
    ActiveList.value.forEach((el) => {
      if (el.member_price_config) {
        el.price = Number(el.member_price_config[`${userInfo.value.member_level}`]);
        price = price + el.num * Number(el.member_price_config[`${userInfo.value.member_level}`]);
      }
    });
  }
  //   ActiveList.value.forEach((el) => {
  //     price = price + el.num * el.price;
  //   });
  price = parseFloat(price.toFixed(2));
  orderPrice.value = price;
  return price;
});
const getPriceNumberreturn = () => {
  let price: any = 0;
  if (userInfo.value.member_level === 1) {
    ActiveList.value.forEach((el) => {
      if (el.member_price_config) {
        el.price = Number(el.member_price_config[`${userInfo.value.member_level}`]);
        price = price + el.num * Number(el.member_price_config['1']);
      }
    });
  } else if (userInfo.value.member_level === 2) {
    ActiveList.value.forEach((el) => {
      if (el.member_price_config) {
        el.price = Number(el.member_price_config['2']);
        price = price + el.num * Number(el.member_price_config['2']);
      }
    });
  } else {
    ActiveList.value.forEach((el) => {
      if (el.member_price_config) {
        el.price = Number(el.member_price_config[`${userInfo.value.member_level}`]);
        price = price + el.num * Number(el.member_price_config[`${userInfo.value.member_level}`]);
      }
    });
  }
  //   ActiveList.value.forEach((el) => {
  //     price = price + el.num * el.price;
  //   });
  price = parseFloat(price.toFixed(2));
  orderPrice.value = price;
  return price;
};
const addSku = () => {
  if (
    selectList.value.sku_list[skuIndex.value].member_price_config &&
    selectList.value.sku_list[skuIndex.value].member_price_config[`${userInfo.value.member_level}`]
  ) {
    let getPrice = Number(
      userInfo.value.member_level === 1
        ? selectList.value.sku_list[skuIndex.value].member_price_config[`${userInfo.value.member_level}`]
        : userInfo.value.member_level === 2
        ? selectList.value.sku_list[skuIndex.value].member_price_config[`${userInfo.value.member_level}`]
        : selectList.value.sku_list[skuIndex.value].member_price_config[`${userInfo.value.member_level}`],
    );

    Number(selectList.value.sku_list[skuIndex.value].member_price_config);
    if (getPrice <= 0) {
      MessagePlugin.warning('当前商品无法选择');
      return;
    }
  } else {
    let getPrice = Number(selectList.value.sku_list[skuIndex.value].price);
    if (getPrice <= 0) {
      MessagePlugin.warning('当前商品无法选择');
      return;
    }
  }
  let isLock = isOpensku_id(selectList.value.sku_list[skuIndex.value].sku_id);
  if (isLock) {
    MessagePlugin.warning('当前商品已存在');
    return;
  }
  let arr = {
    goods_name: selectList.value.goods_name,
    goods_id: selectList.value.goods_id,
    sku_id: selectList.value.sku_list[skuIndex.value].sku_id,
    price: Number(selectList.value.sku_list[skuIndex.value].price),
    goods_image: selectList.value.sku_list[skuIndex.value].sku_image,
    stock: selectList.value.sku_list[skuIndex.value].stock,
    member_price_config: selectList.value.sku_list[skuIndex.value].member_price_config
      ? selectList.value.sku_list[skuIndex.value].member_price_config
      : {
          '1': Number(selectList.value.sku_list[skuIndex.value].price),
          '2': Number(selectList.value.sku_list[skuIndex.value].price),
          '3': Number(selectList.value.sku_list[skuIndex.value].price),
        },

    num: 1,
  };
  ActiveList.value.push(arr);
  skuIndex.value = 0;
  skuNumber.value = 1;
  skuOpen.value = false;
};
const delItem = (index: any) => {
  //删除某个商品
  ActiveList.value.splice(index, 1);
};
const countType = (type: any, index: number) => {
  if (type === 1) {
    if (ActiveList.value[index].num === 1) {
      ActiveList.value.splice(index, 1);
    } else {
      ActiveList.value[index].num = ActiveList.value[index].num - 1;
    }
  } else {
    if (ActiveList.value[index].stock > ActiveList.value[index].num) {
      ActiveList.value[index].num = ActiveList.value[index].num + 1;
    }
  }
};
const addActive = (item: any) => {
  let isLock = isOpen(item.goods_id);

  if (userInfo.value.member_id === 0) {
    MessagePlugin.warning('请先选择用户');
    return;
  }
  // console.log(item.goods_spec_format)
  if (item.goods_spec_format) {
    selectList.value = item;
    skuIndex.value = 0;
    skuNumber.value = 1;
    skuOpen.value = true;
  } else {
    if (isLock) {
      return;
    }
    let getPrice = Number(item.price);
    if (getPrice <= 0) {
      MessagePlugin.warning('当前商品无法选择');
      return;
    }
    let arr = {
      goods_name: item.goods_name,
      goods_id: item.goods_id,
      sku_id: item.sku_id,
      price: Number(item.price),
      goods_image: item.goods_image,
      stock: item.goods_stock,
      member_price_config: item.member_price_config
        ? item.member_price_config
        : {
            '1': Number(item.price),
            '2': Number(item.price),
            '3': Number(item.price),
            '4': Number(item.price),
            '5': Number(item.price),
            '6': Number(item.price),
            '7': Number(item.price),
            '8': Number(item.price),
            '9': Number(item.price),
            '10': Number(item.price),
          },
      num: 1,
    };
    ActiveList.value.push(arr);
  }
};
const setcategory_id = (id: number) => {
  parmas.category_id = id;
  parmas.page = 1;
  getgoodslistsData();
};
const onChangelevel = (e: any, context: any) => {
  vipInfo.member_level_name = context.option.label;
  // console.log(e, )
};
const payList = async () => {
  try {
    if (loading.value) {
      return;
    }
    loading.value = true;
    if (ActiveList.value.length === 0) {
      loading.value = false;
      return;
    }
    let parmas = {
      user: route.query.user,
      discount_money: orderPrice.value,
      member_id: userInfo.value.member_id,
      sku_list: ActiveList.value,
      order_time: orderTime.value,
      adjust_money: preferential.value,
      delivery_money: preferentialNew2.value,
    }; //代付操作
    let data = await createOrder(parmas);
    if (data.code === 0) {
      ActiveList.value = [];
      MessagePlugin.success('下单成功');
      preferential.value = 0;
      preferentialNew2.value = 0;
    }
    loading.value = false;
  } catch {
    loading.value = false;
  }
  //代付操作进行结算
};
const getGoodsSkuInfo = async () => {
  //获取当前sku信息
  // let arr = await getGoodsSku()
};

const getTabList = async () => {
  //获取当前分类
  //  let datas=await
  lists().then((res) => {
    tabList.value = res.data;
    parmas.category_id = tabList.value[0].category_id;
    getgoodslistsData();
  });
  // console.log(datas,'1111111111111')
};
const getvipLists = async () => {
  //获取当前会员级别列表
  let res = await vipLists();
  vipTab.value = res.data;
};
const getgoodslistsData = async () => {
  //获取当前商品列表
  let data = await getgoodslists(parmas);
  // console.log(data)
  goodList.value = data.data.list;
  console.log(data.data.list);
  total.value = data.data.count;
};

getTabList();
getvipLists();
const seachVip = () => {
  if (loading.value) {
    return;
  }
  loading.value = true;
  //通过手机号查询会员
  if (mobile.value.length !== 11 && mobile.value.length !== 4) {
    MessagePlugin.error('请输入正确检索条件');
    loading.value = false;
    return;
  }
  searchMemberByMobile({ mobile: mobile.value }).then((res) => {
    if (res.data) {
      MessagePlugin.success('查询成功');
      userInfo.value = res.data;
      visible.value = false;
      mobile.value = '';
      loading.value = false;
      close();
    } else {
      MessagePlugin.error('未找到用户或手机号输入错误');
      loading.value = false;
    }
  });
};
const addMemberLogin = () => {
  if (loading.value) {
    return;
  }
  loading.value = true;
  if (
    !vipInfo.mobile ||
    !vipInfo.nickname ||
    !vipInfo.member_level ||
    !vipInfo.member_level_name ||
    vipInfo.mobile.length < 11
  ) {
    MessagePlugin.error('请完善信息在进行提交');
    return;
  }
  addMember(vipInfo).then((res) => {
    // console.log(res)
    loading.value = false;
    if (res.data) {
      MessagePlugin.success('创建成功');
      userInfo.value = res.data;
      visible1.value = false;
      close();
    }
  });
};
const calculateGet = () => {
  calculate(LeftList.value).then((res) => {});
};
const onEnter = () => {
  parmas.page = 1;
  getgoodslistsData();
};
const onCurrentChange = (index, pageInfo) => {};

const onChange = (pageInfo) => {
  getgoodslistsData();
};
const cheakout = () => {
  visible.value = false;
  visible1.value = true;
};
</script>

<style lang="less" scoped>
@import './index.less';

:deep(.t-loading__gradient-conic) {
  background: rgba(255, 255, 255, 1) !important;
}
.preferential-box {
  width: 100%;
  display: flex;
  align-items: center;
  flex-direction: column;
}
.preferential-item {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  margin-top: 24px;
}
</style>